package com.suncky.frame.base;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewbinding.ViewBinding;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;

public abstract class BaseViewBindingFragment<B extends ViewBinding> extends BaseFragment{

    private B binding;

    public B getBinding() {
        return binding;
    }

    @SuppressWarnings("unchecked")
    protected B createBinding() {
        try {
            // 获取当前对象的父类类型
            ParameterizedType pt = (ParameterizedType) (this.getClass().getGenericSuperclass());
            if (pt!=null) {
                // 获取第一个类型参数的真实类型
                Class<B> c = (Class<B>) pt.getActualTypeArguments()[0];
                Method method = c.getDeclaredMethod("inflate", LayoutInflater.class);
                return (B) method.invoke(null, getLayoutInflater());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = createBinding();
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    protected View getContentView() {
        if (binding != null) {
            return binding.getRoot();
        }
        return null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (binding != null) {
            binding = null;
        }
    }

    @Override
    protected final int getLayoutResId() {
        return 0;
    }
}
